<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String authServerPath  =(String)request.getSession().getAttribute("authServerPath");
%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="<%=path %>/resource/lib/ligerUI/skins/sqBlue/css/login-new.css">

    <title>狮桥融资租赁系统</title>
    <jsp:include page="../import.jsp" flush="true" />
    <script src="<%=path %>/resource/lib/watchPwd.js" type="text/javascript"></script>
    <script src="<%=path %>/resource/lib/axcam/WsUtil.js" type="text/javascript"></script>
    <script src="<%=path %>/resource/lib/crypto-js.js" type="text/javascript"></script>
    <!-- SESSION 失效后跳出IFRAME 到父级 -->
    <script type="text/javascript">
        if(window != top){
            top.location.href = location.href;
        }
    </script>
    <style>
        .pageFooter{
            width: 100%;
            height: 65px;
            /* background-color: rgba(0, 0, 0, 0.3); */
            background: linear-gradient(to top, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0.3) 50%, rgba(0, 0, 0, 0) 100%);
            font-size: 14px;
            text-align: center;
            line-height: 75px;
            position: absolute;
            bottom: 0;
            left: 0;
            z-index: 10000;
            color: #ffffff;
            box-sizing: border-box;
            /* padding-left: 160px; */
        }
        .pageFooter a{
            color: #ffffff;
        }

        .loginpage .Wrapper .wrap2 .loginWrap {
            top: 48px;
        }

        .loginWrap .fieldset {
            margin-bottom: 5px;
        }

        .loginWrap .fieldset .fieldBox .label .sqIco {
            margin-top: 2px;
        }

        .loginWrap .fieldset .fieldBox {
            margin-bottom: 12px;
        }

        .loginWrap .fieldset .fieldBox .field {
            position: relative;
        }

        .loginWrap .fieldset .fieldBox .field .l-text,
        .loginWrap .fieldset .fieldBox .field .l-text .l-text-field {
            height: 24px;
            line-height: 24px;
        }

        .loginWrap .fieldset .fieldBox .field .l-text .l-text-field::-webkit-input-placeholder {
            color: #aaa;
        }

        .loginWrap .fieldset .fieldBox .field .getVerifyCd {
            position: absolute;
            right: 5px;
            top: 5px;
            cursor: pointer;
        }

        .loginWrap .fieldset .fieldBox .field .getVerifyCd::before {
            content: '';
            display: inline-block;
            position: absolute;
            left: -7px;
            top: 50%;
            margin-top: -6px;
            height: 12px;
            margin-right: 3px;
            border-left: 1px solid #aaa;
        }

        .loginWrap .fieldset .fieldBox .field .getVerifyImg {
            position: absolute;
            right: -83px;
            top: 0;
            margin-left: 5px;
            cursor: pointer;
        }
        .disabledBtn {
            pointer-events: none;
            cursor: default;
            opacity: 0.6;
        }
        <c:if test="${loginType=='scancode'||loginType=='all' }">
        .PassWordLoginWrap{
            display: none;
        }
        </c:if>
        .QRLoginWrap{
            /* width: 100%;
            height: 100%;
            display: none;*/
            top: 50px!important;
            padding-right: 96px;
            box-sizing: border-box;
            margin-left: 120px!important;
        }
        .QRLoginWrap .pic{
            width: 100%;
            position: relative;
        }
        .QRLoginWrap img{
            display: block;
            width: 100%;
        }
        .QRLoginWrap .reload_qr, .QRLoginWrap .qrcode_succ{
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: none;
        }
        .QRLoginWrap .reload {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            font-size: 14px;
            color: #ffffff;
            background-color: rgba(0, 0, 0, 0.6);
        }
        .QRLoginWrap .reload .reload_txt{
            margin-bottom: 20px;
        }
        .QRLoginWrap .reload .reload_btn{
            padding: 0 20px;
            line-height: 28px;
            border-radius: 14px;
            background-color: rgba(66, 177, 127, 1);
            cursor: pointer;
        }
        .QRLoginWrap .reload .reload_icon{
            width: 50px;
            height: 50px;
            margin-bottom: 20px;
        }
        .tabs_view{
            position: absolute;
            top: 0px;
            left: 50%;
            z-index: 5;
            margin-left: 72px;
            width: 254px;
        }
        .tabs_view li{
            width: 50%;
            float: left;
            height: 42px;
            line-height: 42px;
            text-align: center;
            font-size: 15px;
            cursor: pointer;
            color: #ddd;
            background-color: rgba(66, 177, 127, 1);
        }
        .tabs_view li span{
            padding: 10px 8px;
            line-height: 42px;
        }
        .tabs_view li.active span{
            color: #ffffff;
            border-bottom: solid 2px #ffffff;
        }
    </style>
</head>
<body class="loginpage">
<div class="Wrapper">
    <div class="wrap2">
        <ul class="tabs_view" id="tabs_view">
            <c:if test="${loginType=='all' }">
                <li class="active">
                    <span>扫码登录</span>
                </li>
            </c:if>

            <c:if test="${loginType=='scancode' }">
                <li>
                    <span>扫码登录</span>
                </li>
            </c:if>
            <c:if test="${loginType=='password'||loginType=='all' }">
                <li>
                    <span>密码登录</span>
                </li>
            </c:if>
        </ul>
        <c:if test="${loginType=='scancode'||loginType=='all' }">
        <div class="loginWrap QRLoginWrap loginWrap_view">
            <div class="pic">
                <div class="reload_qr" id="reload_qr">
                    <div class="reload">
                        <div class="reload_txt">登录失败</div>
                        <div class="reload_btn" id="reload_btn">刷新</div>
                    </div>
                </div>
                <div class="qrcode_succ" id="qrcode_succ">
                    <div class="reload">
                        <div class="reload_icon"><img src="../lib/images/qrcode-succ.png" alt=""></div>
                        <div class="reload_succ">扫描成功!</div>
                    </div>
                </div>
                <img id="qrcodeImg" src="" alt="">
                <input id="qrcodeId" type="hidden"/>
            </div>
        </div>
        </c:if>
        <c:if test="${loginType=='password'||loginType=='all' }">
        <div class="loginWrap PassWordLoginWrap loginWrap_view">
            <form id="formSet1">
                <div class="fieldset">
                    <div class="fieldBox">
                        <div class="label"><i class="sqIco sqIco_user"></i></div>
                        <div class="field">
                            <input name="usrNm" id="usrNm" type="text" class="ui-textbox"
                                   value="" placeholder="请填写用户名" validate="{required:true, maxlength:20}">
                        </div>
                    </div>
                    <div class="fieldBox" style="height: 33px;">
                        <div class="label"><i class="sqIco sqIco_pw"></i></div>
                        <div class="field">
                            <input name="pwd" id="pwd" type="password" class="ui-password" data-watch-pwd="login"
                                   value="" placeholder="请填写密码" validate="{required:true, maxlength:20}"
                                   oncontextmenu="return false" oncopy="return false" oncut="return false">
                        </div>
                    </div>
                    <div class="fieldBox" id="verifyView">
                        <div class="label"><i class="sqIco sqIco_verifyImg"></i></div>
                        <div class="field">
                            <input name="verifyImg" id="verifyImg" type="text" class="ui-textbox"
                                   value="" placeholder="图片验证码" validate="{required:true, maxlength:4}"
                                   ligerui="width:80">
                            <span class="getVerifyImg">
                                 <img width="80" height="24" id="kaptcha" onClick="changeKaptcha()"
                                      src=<%=authServerPath%>+"/user/sysUsr/getCaptcha"/>
                             </span>
                        </div>
                    </div>
                    <div class="fieldBox">
                        <div class="label"><i class="sqIco sqIco_verifyCd"></i></div>
                        <div class="field">
                            <input name="verifyCd" id="verifyCd" type="text" class="ui-textbox"
                                   value="" placeholder="手机验证码" validate="{required:true, maxlength:4}">
                            <span class="getVerifyCd" onclick="getPhoneCode(this)">获取验证码</span>

                        </div>
                    </div>
                </div>
                <div class="btnsWrap">
                    <span id="login_btn" onclick="login();" class="sq-button rounded co_orangeGR">登 录</span>
                    <span>
                        <input id="rememberme" name="rememberme" type="checkbox"/>记住账号
                    </span>
                    <span>
                        <a href="javascript:;" onclick="toUsrPwdReset()" style="font-weight: bold;font-size:15px;">忘记密码</a>
                    </span>
                </div>
            </form>
        </div>
        </c:if>
    </div>
    <div class="pageFooter">
        <p>狮桥资本@2012 All rights reserved. <a href="https://www.beian.miit.gov.cn/" target="_blank">津ICP备15008226号-2</a></p>
    </div>
</div>
<script>
    //登录轮询定时器Id
    var isLoginTimerId;
    //二维码过期定时器Id
    var isExpireTimerId;
    //二维码是否已过期
    var qrcodeExpired = false;
    $(function() {
        createEye('<%=path %>')
        //初始化数据
        initEvent();
        <c:if test="${loginType=='scancode'||loginType=='all' }">
            loadQrcode()
        </c:if>
        <c:if test="${loginType=='all' }">
        var tabs = $("#tabs_view li")
        var loginWrap = $('.loginWrap_view')
            tabs.on('click', function (event) {
                var e = $(this)
                if (!e.hasClass('active')) {
                    var ind = e.index()
                    e.addClass('active').siblings().removeClass('active')
                    loginWrap.eq(ind).show().siblings('.loginWrap_view').hide()
                }

            })
        </c:if>


        // 显示/隐藏  dom:(需要显示和隐藏的元素)  status:( 0:隐藏 1:显示)
        // 调用方法：
        // isShow('#reload_qr', 1)
        // or
        // isShow($('#reload_qr'), 1)
        // function isShow(dom, status) {
        //     var reloadDom = $(dom)
        //     if (status) {
        //         reloadDom.show()
        //         return
        //     }
        //     reloadDom.hide()
        // }

        // 刷新二维码按钮
        $('#reload_btn').on('click', function(){
            isShow('#reload_qr', 0)
            loadQrcode();
        })

        var ligerForm = $("#formSet1").ligerForm({
            inputWidth: 165,
            validate: {
                errorPlacement: function (lable, element)
                {
                    if (!$(lable).html()) return;
                    if (!element.attr("id")){
                        var eleid = new Date().getTime();
                        element.attr("id", eleid);
                        lable.attr("for", eleid);
                    }
                    if (element.hasClass("l-text-field")){
                        element.parent().addClass("l-text-invalid");
                    }
                    $(element).removeAttr("title").ligerHideTip();
                }
            },
            onAfterSetFields: function () {
                set_userName();
            }
        });

    });

    //初始化事件
    function initEvent(){
        $("form").on('keydown', function(event) {
            if (event.keyCode == 13){
                event.preventDefault();
                //$("#login_btn").click();
                login();
            }
        });
        $("#verifyView").hide()
    }
    function Encrypt(word, keyStr, ivStr) {
        let key = CryptoJS.enc.Utf8.parse(keyStr)
        let iv = CryptoJS.enc.Utf8.parse(ivStr)
        let srcs = CryptoJS.enc.Utf8.parse(word)
        // 加密模式为CBC，补码方式为PKCS5Padding（对应PKCS7）
        let encrypted = CryptoJS.AES.encrypt(srcs, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
        })
        // 返回base64
        return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
    }
    //登录
    function login(){
        var _usrNm = $("#usrNm").val();
        var _pwd = $("#pwd").val();
        var _verifyCd=$("#verifyCd").val();
        var _sqid = getSQID();

        if(_usrNm.trim() == ""){
            top.$.ligerDialog.SQalert({content: LogUtils.LOG_USER_LOGIN_INPUT_USER_NAME, SQ_type: "warning"});
            return;
        }

        if(_pwd.trim() == ""){
            top.$.ligerDialog.SQalert({content: LogUtils.LOG_FLOW_LOGIN_INPUT_USER_PWD, SQ_type: "warning"});
            return;
        }

        if ($("#login_btn").attr("disabled") == "disabled") {
            UIUtils.alertSuccess(LogUtils.LOG_FLOW_LOGIN_WAITING);
            return;
        }

        //禁用按钮login_btn
        $("#login_btn").attr("disabled", "disabled");

        var _url = <%=authServerPath%>+"/user/sysUsr/login";
        var pwd64=base64Encode(_pwd);
    //秘钥
        var aesKey = "lionbridgecapita";
        var aesPwd =Encrypt(_pwd,aesKey,aesKey);

        $.ajax({
            type : 'post',
            dataType : 'json',
            headers:{
                SQID: _sqid,
                sysCd:11000
            },
            data : {
                usrNm : _usrNm,
                pwd:aesPwd,
                sysCd:11000,
                smsCaptcha:_verifyCd
            },
            url : _url,
            success : function(msg) {
                if (msg.success == 1) {
                    //清除tab页签 liger-home-tab
                    CookieUtils.remote("liger-home-tab");
                    document.write("<form action='<%=path%>/login/login/toIndexPage.do' method=post name=form1 style='display:none'>");
                    document.write("<input type=hidden name=SQID value='"+_sqid+"'>");
                    document.write("<input type=hidden name=sysCd value='"+11000+"'>");
                    document.write("</form>");
                    document.form1.submit();
                } else {
                    top.$.ligerDialog.SQalert({content: msg.info,SQ_type: "error"});
                    //启用按钮login_btn
                    $('#login_btn').removeAttr("disabled");
                }
            }
        });
    }

    function set_userName () {
        var c_userName = $.cookie('userName');
        if (c_userName) {
            liger.get("usrNm").setValue(c_userName);
            liger.get("rememberme").setValue(true);
        };
    }
    function set_rememberme (checked, userName) {
        if (checked) {
            $.cookie('userName', userName , {expires: 7});
        }else{
            $.cookie('userName', null);
        };
    }

    function toUsrPwdReset() {
        $.ligerDialog.SQopen({
            width: 800,
            height:600,
            title : '重置密码',
            url:'<%=path%>/system/sysUsrPwd/toVerifyIdentityPage.do',
            // 自定义buttons的时候 不要设置 fixButtons: true
            buttons: [
                {
                    text: "重置密码", type: 'cancel', cls: 'l-dialog-btn-no',
                    onclick: function (item, Dialog) {
                        //在子页面里绑定 frameElement.dialog.onCancel = function () {}
                        if (Dialog.onOk) {
                            Dialog.onOk()
                        };
                    }
                },{
                    text: "取消", type: 'cancel', cls: 'l-dialog-btn-no',
                    onclick: function (item, Dialog) {
                        //在子页面里绑定 frameElement.dialog.onCancel = function () {}
                        if (Dialog.onCancel) {
                            Dialog.onCancel()
                        };
                    }
                }
            ]
        });
    }

    function getSQID(){
        var _url = <%=authServerPath%>+"/user/sysUsr/getSQID";
        var SQID = $.cookie("FL_SQID");
        if(null == SQID|| "" == SQID){
            $.ajax({
                type : 'get',
                url : _url,
                async:false,
                success : function(msg) {
                    if (msg.success == 1) {
                        SQID = msg.data
                        $.cookie("FL_SQID",SQID,{expires: 0.02083333, path: '/'});
                    } else {
                        top.$.ligerDialog.SQalert({content: msg.info,SQ_type: "error"});
                    }
                }
            });
        }
        return SQID;
    }
    /*
    *获取手机验证码
    */
    function getPhoneCode(obj) {
        var SQID = getSQID();
        var _verifyImg=$("#verifyImg").val();
        var _usrNm = $("#usrNm").val();
        if(_usrNm == "" || _usrNm == null || _usrNm == undefined){
            top.$.ligerDialog.SQalert({content: "请输入用户名", SQ_type: "warning"});
            return;
        }else{
            var _url = <%=authServerPath%>+"/user/sysUsr/getAuthCd";
            $.ajax({
                type : 'get',
                headers:{
                    SQID:SQID,
                    sysCd: 11000
                },
                data : {
                    sysCd: 11000,
                    usrNm : _usrNm,
                    verifyImg:_verifyImg
                },
                url : _url,
                success : function(msg) {
                    if(msg.data==1){
                        var fieldBoxList = document.getElementsByClassName("fieldBox")
                        for (var i = 0, len = fieldBoxList.length; i < len; i++) {
                            console.log(fieldBoxList[i])
                            fieldBoxList[i].style.marginBottom = 5 + "px"
                        }
                        $("#verifyView").show();
                        changeKaptcha();
                    }
                    if (msg.success == 1) {
                        top.$.ligerDialog.SQalert({content: msg.info, SQ_type: "success"});
                        settime(obj);
                    }else if(msg.success == 3){
                        top.$.ligerDialog.SQalert({content: msg.info, SQ_type: "success",SQ_showButtons: true});
                    } else {
                        top.$.ligerDialog.SQalert({content: msg.info,SQ_type: "error",SQ_showButtons: true});
                    }
                }
            });
        }
    }

    var countdown = 60;

    function settime(obj) { //发送验证码倒计时
        debugger
        if (countdown == 0) {
            $(obj).removeClass("disabledBtn")
            $(obj).text("获取验证码");
            countdown = 60;
            return;
        } else {
            $(obj).addClass("disabledBtn")
            $(obj).text("重新发送(" + countdown + ")");
            countdown--;
        }
        setTimeout(function () {
            settime($(obj))
        }, 1000)
    }

    /*
     *更新图片验证码
     */
    function changeKaptcha(){
        var SQID = getSQID();
        // var _usrNm = $("#usrNm").val();
        //每次请求需要一个不同的参数，否则可能会返回同样的验证码
        //这和浏览器的缓存机制有关系，也可以把页面设置为不缓存，这样就不用这个参数了。
        <%--obj.src= <%=authServerPath%>+"/login/login/kaptcha.do?usrNm="+_usrNm+"&r=" + Math.floor(Math.random() * 100);--%>
        $.ajax({
            type : 'get',
            headers: {
                SQID: SQID,
                sysCd: 11000
            },
            url : <%=authServerPath%>+"/user/sysUsr/getCaptcha",
            success : function(msg) {
                if (msg.success == 1) {
                    $("#kaptcha").attr("src","data:image/gif;base64,"+msg.data);
                } else {
                    top.$.ligerDialog.SQalert({content: msg.info,SQ_type: "error"});
                }
            }
        });


    }

    /**
     * 加载登录二维码
     */
    function loadQrcode() {
        var osName = TClientCheck_OS()
        var url = <%=authServerPath%>+"/user/sysUsr/qrCode/generate";
        var params = {
            "sysCd":"11000",
            "osName": osName
        };
        $.ajax({
            type: 'post',
            url: url,
            timeout: 5000,
            data: params,
            dataType: "json",
            success: function (response) {
                if ("1" == response.success) {
                    var qrcodeInfo = response.data;
                    var qrcodeId = qrcodeInfo.qrcodeId;
                    var qrcodeImgUrl = qrcodeInfo.dataUrl;
                    $("#qrcodeImg").attr("src", "data:image/gif;base64,"+qrcodeImgUrl);
                    $("#qrcodeId").val(qrcodeId);
                    //1.启动对应的二维码是否已登录的验证
                    isLoginTimerId = setInterval(qrcodeIsLogined, 3000);
                    //2.设置二维码过期时间
                    isExpireTimerId = setTimeout(qrcodeIsExpired, 60000);
                    qrcodeExpired = false;
                } else {
                    top.$.ligerDialog.SQalert({content: response.info,SQ_type: "error",SQ_showButtons: true});
                }
            },
            error: function (msg) {
                top.$.ligerDialog.SQalert({content: "网络异常，请稍后重试...",SQ_type: "error",SQ_showButtons: true});
            }
        });
    }

    /**
     * 轮询二维码是否已登录
     */
    function qrcodeIsLogined() {
        var qrcodeId = $("#qrcodeId").val();
        var url = <%=authServerPath%>+"/user/sysUsr/qrCode/state";
        $.ajax({
            type: 'post',
            url: url,
            timeout: 5000,
            data: {
                "sysCd":"11000",
                "qrCodeId": qrcodeId
            },
            dataType: "json",
            success: function (response) {
                if ("1" == response.success) {
                    var code = response.data.code;
                    if("1" == code){
                        //已经扫描
                        if(!qrcodeExpired){
                            coverQrcodeInfo("扫描成功，等待确认", 0)
                        }
                    }
                    if("2" == code){
                        //取消登陆
                        clearInterval(isLoginTimerId);
                        clearTimeout(isExpireTimerId);
                        coverQrcodeInfo("登录失败", 1)
                    }
                    if("3" == code){
                        //确认登录
                        clearInterval(isLoginTimerId);
                        clearTimeout(isExpireTimerId);
                        qrcodeLogin(qrcodeId)
                    }
                    if("4" == code){
                        //二维码已失效
                        qrcodeIsExpired()
                    }
                }
            }
        });
    }

    /**
     * 二维码过期设置
     */
    function qrcodeIsExpired() {
        coverQrcodeInfo("二维码已失效", 1)
        qrcodeExpired = true;
        clearInterval(isLoginTimerId);
        clearTimeout(isExpireTimerId);
    }

    //登录
    function qrcodeLogin(qrcodeId){
        var _url = <%=authServerPath%>+"/user/sysUsr/qrCode/login";
        $.ajax({
            type : 'get',
            dataType : 'json',
            data : {
                sysCd:"11000",
                qrCodeId:qrcodeId
            },
            url : _url,
            success : function(msg) {
                if (msg.success == 1) {
                    //清除tab页签 liger-home-tab
                    CookieUtils.remote("liger-home-tab");
                    document.write("<form action='<%=path%>/login/login/toIndexPage.do' method=post name=form2 style='display:none'>");
                    document.write("<input type=hidden name=SQID value='"+qrcodeId+"'>");
                    document.write("<input type=hidden name=sysCd value='"+11000+"'>");
                    document.write("</form>");
                    document.form2.submit();
                } else {
                    coverQrcodeInfo("登录失败", 1)
                }
            }
        });
    }

    function isShow(dom, status) {
        var reloadDom = $(dom)
        if (status) {
            reloadDom.show()
            return
        }
        reloadDom.hide()
    }

    function coverQrcodeInfo(msg, state) {
        isShow('#reload_qr', 1)
        isShow('#reload_btn', state)
        $(".reload_txt").html(msg)
    }

    function TClientCheck_OS() {
        var sUA= navigator.userAgent.toLowerCase();
        if(sUA.indexOf( 'win' ) !=-1){
            return "Windows";
        }
        if(sUA.indexOf('linux')!=-1) {return 'Linux';}
        if(sUA.indexOf("freebsd")!=-1) {return 'FreeBSD';}
        if(sUA.indexOf( 'x11' )!=-1) {return 'Unix';}
        if(sUA.indexOf('mac') != -1) {return "Mac"; }
        if(sUA.indexOf("sunos")!=-1) {return 'Sun OS';}
        if((sUA.indexOf("os/2")!=-1) || (navigator.appVersion.indexOf("OS/2")!=-1) || (sUA.indexOf("ibm-webexplorer")!=-1)) {return "OS 2"}
        if(navigator.platform == 'PalmOS' ) {return 'Palm OS'; }
        if((navigator.platform == 'WinCE' ) || ( navigator.platform == 'Windows CE' ) || ( navigator.platform == 'Pocket PC' ) ) {return 'Windows CE';}
        if(sUA.indexOf( 'webtv')!=-1) {return 'WebTV Platform'; }
        if(sUA.indexOf( 'netgem')!=-1) {return 'Netgem';}
        if(sUA.indexOf( 'opentv')!=-1) {return 'OpenTV Platform';}
        if(sUA.indexOf( 'symbian')!=-1) {return 'Symbian';}
        return "Unknown";
    }
</script>
</body>
</html>